package com.willowandcreek.addongenie.google;

import java.net.URL;
import java.util.logging.Logger;

import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
import com.google.gdata.data.docs.FolderEntry;

public class Repository {
	private static final Logger LOGGER = Logger.getLogger(Repository.class
			.getName());

	private static Repository INSTANCE = null;
	private static final String ROOT_FOLDER_NAME = "AddonGenie";
	private DocumentListEntry rootFolderEntry = null;

	private DocsService docsService;

	public static Repository instance() throws Exception {
		if (INSTANCE == null)
			INSTANCE = new Repository();

		return INSTANCE;
	}

	private Repository() throws Exception {
		LOGGER.info("Initializing repository...");
		docsService = Services.getDocsService();
		validateFolderStructure();
		loadGenieSettings();
	}

	private void validateFolderStructure() throws Exception {
		LOGGER.info("Validating folder structure...");
		URL feedUri = new URL("https://docs.google.com/feeds/default/private/full/-/folder?title='" + ROOT_FOLDER_NAME + "'");
		DocumentListFeed feed = docsService.getFeed(feedUri, DocumentListFeed.class);		

		if (feed.getEntries().size() == 1) {
			rootFolderEntry = feed.getEntries().get(0);
		} else if (feed.getEntries().size() == 0) {
			LOGGER.info("Creating ROOT folder");
			createFolder(ROOT_FOLDER_NAME);
		} else {
			throw new Exception("Unexpected situation. Multiple feed entries received for genie root");
		}
	}
	
	private void loadGenieSettings() throws Exception {
		LOGGER.info("Loading Genie settings...");
		URL feedUri = new URL("https://docs.google.com/feeds/default/private/full/-/folder");
		
	}

	private void createFolder(String folderName) throws Exception {
		DocumentListEntry newEntry = new FolderEntry();
		newEntry.setTitle(new PlainTextConstruct("AddonGenie"));
		URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
		docsService.insert(feedUrl, newEntry);
	}
}
